// 路由器
const routes = require('./routes.js')

module.exports = {
  routes,
  // 获取匹配路由
  matchRoute (pathname, method) {
    let route = routes.find(item => {
      if (String(item.method).toLowerCase() !== method) {
        return false
      }
      if (item.path === pathname) {
        return true
      }
      if (item.path instanceof RegExp && item.path.test(pathname)) {
        return true
      }
      // 支持参数路由匹配
      if (item.path.includes(':')) {
        let pattern = item.path.replace(/:[^/]+/g, '([^/]+(?:/[^/]+)*)')
        let regex = new RegExp('^' + pattern + '$')
        if (regex.test(pathname)) {
          // 提取参数
          let matches = pathname.match(regex)
          if (matches) {
            let paramNames = item.path.match(/:[^/]+/g) || []
            item.params = {}
            paramNames.forEach((paramName, index) => {
              let key = paramName.substring(1) // 去掉冒号
              item.params[key] = matches[index + 1]
            })
          }
          return true
        }
      }
      return false
    })
    return route
  },
  // 执行路由
  run (route, req, res) {
    let instance = null
    if (route.name) {
      instance = this[route.name]
      if (!instance) {
        instance = new route.service()
        this[route.name] = instance
      }
    } else {
      if (!route.instance) {
        route.instance = new route.service()
      }
      instance = route.instance
    }
    // 将路由参数添加到请求对象中
    if (route.params) {
      req.routeParams = route.params
    }
    return instance[route.action](req, res)
  }
}